﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using ServerLibrary.Abstract;
using ServerLibrary.Infrastructure;
namespace ServerLibrary.Concrete
{
    /// <summary>
    /// Implements TaskHandler.
    /// </summary>
    public class TaskHandler : ITaskHandler
    {
    
        public event TaskFinishedHandler TaskFinished;

        public int ActiveTaskCount
        {
            get { return taskNumber; }
        }
        
        public void AddTask(ITask task)
        {
            taskNumber += 1;
            task.TaskDone+=new TaskDoneHandler(this.OnTaskDone);
            ThreadPool.QueueUserWorkItem(task.Run, task);
        }        

        public bool SetMaxThreads(int workerThreads, int completionPortThreads)
        {
            return ThreadPool.SetMaxThreads(workerThreads, completionPortThreads);
        }

    
        public bool SetMinThreads(int workerThreads, int completionPortThreads)
        {
            return ThreadPool.SetMinThreads(workerThreads, completionPortThreads);
        }


        public int GetAvailableThreads()
        {
            int workerThreads;           
            int portThreads;
            ThreadPool.GetAvailableThreads(out workerThreads, out portThreads);
            return workerThreads;
        }

        /// <summary>
        /// Raises when task is done.
        /// </summary>
        /// <param name="sender">Task object.</param>
        /// <param name="e">Some arguments.</param>
        private void OnTaskDone(object sender, EventArgs e)
        {
            taskNumber -= 1;
            SetTaskFinished();
        }

        /// <summary>
        /// Raise TaskFinishedEvent.
        /// </summary>
        private void SetTaskFinished()
        {
            if (TaskFinished != null)
            {
                TaskFinished(this, new TaskHandlerEventArguments() { });
            }
        }

        /// <summary>
        /// Number of tasks.
        /// </summary>
        private int taskNumber = 0;
    }
}
